package com.ferrlo.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ferrlo.model.Project;
import com.ferrlo.service.IProjectManager;
import com.ferrlo.service.impl.ProjectManager;

@Controller
public class ToProjectDetailsController {
	
	@Resource(name="projectManager")
	private IProjectManager projectManager;
	
	
	@RequestMapping(value="/toProjectDetails")
	public String toProjectDetails(HttpServletRequest request){
		
		String pid = request.getParameter("pid");
		Project project = findProjectByPid(pid);
		if (project == null) {
			System.out.println("=== Project fail ===");
			return "index";
		}else {
			request.setAttribute("project", project);
			return "projectDetails";
		}

	}

	
	@RequestMapping(value="/toProjectDetails.json")
	@ResponseBody
	public Map<String, Object> toProjectDetails_JSON(HttpServletRequest request){
		Map<String, Object> map = new HashMap<String, Object>();
		
		String pid = request.getParameter("pid");
		Project project = findProjectByPid(pid);
		if (project == null) {
			System.out.println("=== Project fail ===");
			map.put("msg", "fail");
		}else {
			request.setAttribute("project", project);
			map.put("msg", "success");
			map.put("project", project);
		}
		
		return map;
	}
	
	
	
	private Project findProjectByPid(String pid){
		String dqQuery = "";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", "pid");
		List<Project> projects = projectManager.findListByDynamicQuery(dqQuery, map);
		if (projects.size() != 0) {
			return projects.get(0); 
		}
		return null;
	}
	
}
